import React, { useState, useEffect } from "react";
import { Route, Routes, useNavigate, Link } from 'react-router-dom';
import { Button, Drawer, Form, Avatar, Divider, List, Space, message } from 'antd';
import InfiniteScroll from 'react-infinite-scroll-component';
import { PlusOutlined, LikeOutlined, MessageOutlined, FormOutlined, DeleteOutlined, EyeOutlined, LikeFilled } from '@ant-design/icons';
import intl from 'react-intl-universal';
import $ from 'jquery';
import ArticleEdit from "./addArticleDrawer";
import ArticleUpdate from "./updateArticleDrawer";
import { storage } from "../../utils/localstorage";
import './article.css';


const Article = () => {
  

  // 根据用户名称、用户角色，获取文章数据
  const [hasChange, setHasChange] = useState(true);
  const [articleData, setArticleData] = useState([]);
  useEffect(() => {
    const getArticleData = () => {
      let userData = storage.get('user');
      if (userData === undefined || userData === null) {
        alert(intl.get('messageOfLogin'));
        window.location.replace('/login');
        return;
      }
      let author = null;
      if (userData.roles.roleName.indexOf('root') === -1) {       // 非超级管理员，只允许对自己的文章进行编辑、删除
        author = userData.username;
      }
      $.ajax({
        url: '/home/article',
        type: 'post',
        data: { 'author': author },
        dataType: 'json',
        success: function(result) {
          if (result.status === 1) {
            setArticleData(result.data);
            // console.log('article',result.data)
          }
        },
        error: function(err) {
          alert(JSON.stringify(err));
        },
      });
    };
    hasChange && getArticleData();
    setHasChange(false);
  }, [hasChange]);


  // 文章列表
  const data = articleData.map((item) => ({
    // href: '/details/' + item.aid,
    id: item.aid,
    title: item.title,
    summary: item.summary,
    content: item.content,
    cover: item.cover,
    author: item.author,
    kind: item.kind,
    views: item.views,
    likes: item.likes,
    comments: item.comments,
  }));


  // 修改文章，传递文章数据
  const [editData, setEditData] = useState();
  const editArticle = (data) => {
    // console.log('edit', data)
    setEditData({
      id: data.id,
      title: data.title,
      summary: data.summary,
      text: data.content,
      cover: data.cover,
      author: data.author,
      kind: data.kind,
    });
    showDrawerII();
  };


  // 删除文章
  const deleteArticle = (id, author) => {
    // console.log('id')
    let data = {};
    let user = storage.get('user');
    if (user.username === author) {
      data = {id: id, uid: user.uid, type: 2};
    } else {
      data = {id: id};
    }
    $.ajax({
      url: '/home/article/delete',
      type: 'post',
      data: data,
      dataType: 'json',
      success: function(result) {
        if (result.status === 1) {
          message.success(intl.get('succeedToDelete'));
          setHasChange(true);
        } else {
          message.info(intl.get('failedToDelete'));
        }
      },
      error: function(err) {
        alert(JSON.stringify(err));
      },
    });
  };


  // 创作文章时，弹出的抽屉
  const [drawerVisible, setDrawerVisible] = useState(false);
  const showDrawer = () => {
    setDrawerVisible(true);
  };
  const closeDrawer = () => {
    setDrawerVisible(false);
  };

  
  // 修改文章时，弹出的抽屉
  const [drawerVisibleII, setDrawerVisibleII] = useState(false);
  const showDrawerII = () => {
    setDrawerVisibleII(true);
  };
  const closeDrawerII = () => {
    setDrawerVisibleII(false);
    setEditData();
  }


  // 点赞。id即文章id；type即类型，1表示点赞，-1表示取消点赞
  const doLike = (id, type) => {
    let data = {};
    if (type === 1) {
      data = {uid:storage.get('user').uid, aid:id, type:type, pType:3};
    } else {
      data = {uid:storage.get('user').uid, aid:id, type:type, pType:4};
    }
    $.ajax({
      url: '/home/article/like',
      type: 'post',
      data: data,
      dataType: 'json',
      success: function(result) {
        setHasChange(true);
      },
      error: function(err) {
        message.info('网络繁忙，请稍后再试');
      }
    })
  };


  // 浏览文章，浏览量+1，作者积分增加
  const readOnce = (id, author) => {
    $.ajax({
      url: '/home/article/read',
      type: 'post',
      data: {aid:id, author:author},
      dataType: 'json',
      success: function(result) {
        setHasChange(true);
      },
    });
  };


  return (
    <div style={{ backgroundColor: '#FFF', }}>
      <div>
        <Button type="primary" onClick={showDrawer} icon={<PlusOutlined />} className='createArticle'>
          {intl.get('createArticle')}
        </Button>
      </div>
      <div id="scrollableDiv" style={{ height: '700px', overflow: 'scroll', padding: '0 16px', border: '1px solid rgba(140, 140, 140, 0.35)', }}>
        <InfiniteScroll dataLength={data.length} hasMore={data.length < 15}
          endMessage={<Divider plain>It is all, nothing more 🤐</Divider>}
          scrollableTarget="scrollableDiv"
        >
          <List
            itemLayout="vertical"
            size="large"
            loading={false}
            dataSource={data}
            renderItem={(item) => (
              <List.Item
                key={item.id} 
                actions={[
                  <Space>
                    <EyeOutlined className='view' />
                    {item.views}
                  </Space>,
                  <Space>
                    { 
                      (item.likes.indexOf(storage.get('user').uid) === -1) ? 
                      <LikeOutlined className='like' onClick={() => doLike(item.id, 1)} /> : 
                      <LikeFilled className='like' onClick={() => doLike(item.id, -1)} style={{color:'red'}} />
                    }
                    {item.likes.length}
                  </Space>,
                  <Space>
                    <MessageOutlined className='comment' />
                    {item.comments.length}
                  </Space>,
                  <Space>
                    <FormOutlined className='editArticle' onClick={() => editArticle(item)} />
                    {intl.get('editArticle')}
                  </Space>,
                  <Space>
                    <DeleteOutlined className='deleteArticle' onClick={() => deleteArticle(item.id, item.author)} />
                    {intl.get('deleteArticle')}
                  </Space>
                ]}
                extra={<img width={272} height={120} alt="cover" src={item.cover} />}
              >
                <Link to={`/details/${item.id}`} target='_blank' onClick={() => readOnce(item.id, item.author)}>
                  <List.Item.Meta title={item.title} description={item.summary} />
                  {/* {item.content} */}
                </Link>
              </List.Item>
            )}
          />
        </InfiniteScroll>
      </div>
      <Drawer title="发布文章" width={'80%'} onClose={closeDrawer} visible={drawerVisible}
        bodyStyle={{ paddingBottom: 80, }} destroyOnClose={true}
      >
        <ArticleEdit closeDrawer={closeDrawer} setHasChange={setHasChange} />
      </Drawer>
      <Drawer title="编辑文章" width={'80%'} onClose={closeDrawerII} visible={drawerVisibleII}
        bodyStyle={{ paddingBottom: 80, }} destroyOnClose={true}
      >
        <ArticleUpdate closeDrawer={closeDrawerII} setHasChange={setHasChange} data={editData} />
      </Drawer>
    </div>
  );
};

export default Article;